/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.se.server;

import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import cn.ac.iie.di.ban.commons.RuntimeEnv;
import cn.ac.iie.di.ban.config.Configuration;
import cn.ac.iie.di.ban.handler.HttpSe2DBHandler;
import cn.ac.iie.di.ban.metastore.Load2DBEntity;
import java.io.File;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author ulss
 */
public class Http2MetaDB {

    public static Map<String, HttpSe2DBHandler> httpSe2DBHandlerSet = new HashMap<String, HttpSe2DBHandler>();
    static volatile boolean stopped;

    private static org.apache.log4j.Logger logger = Logger.getLogger(Http2MetaDB.class.getName());
    public static String confPath;

    public static void showUsage() {
        System.out.println("Usage:java -jar ");
    }

    public static void main(String[] args) {
        Http2MetaDB.confPath = args[0];
//        Http2MetaDB.confPath = "C:\\Users\\gjw\\Desktop\\projects\\ban-zzpt-metadata-db\\src\\main\\resources";
        PropertyConfigurator.configure(Http2MetaDB.confPath + File.separator + "log4j.properties");
        try {
            init();
            startup();
        } catch (Exception ex) {
            logger.error("starting newmpp is failed for " + ex.getMessage(), ex);
        }
        System.exit(0);
    }

    private static void startup() throws Exception {
        logger.info("checking newmpp rule in metastore....");
        Map<String, Load2DBEntity> se2DBRuleSet = RuntimeEnv.metaStoreManager.getLoad2DBRules();
        if (se2DBRuleSet != null && !se2DBRuleSet.isEmpty()) {
            logger.info("found " + se2DBRuleSet.size() + " new rules");
            for (Map.Entry<String, Load2DBEntity> entry : se2DBRuleSet.entrySet()) {
                HttpSe2DBHandler mqHandler = HttpSe2DBHandler.getHttpSe2MqHandler(entry.getValue());
                httpSe2DBHandlerSet.put(entry.getKey(), mqHandler);
            }
            HttpSe2DBHandler.startReceiveMsg();
        } else {
            logger.error("no new load rules was found and project is stopped!");
            System.exit(0);
        }

        while (true) {
            Long time = System.currentTimeMillis();
            if (time % 80000 == 0) {
                System.gc();
            }
            if (stopped) {
                logger.info("stop receive...");
                for (String httpSe2DBHandler : httpSe2DBHandlerSet.keySet()) {
                    logger.info("stop handler " + httpSe2DBHandler);
                    httpSe2DBHandlerSet.get(httpSe2DBHandler).stop();
                }
                HttpSe2DBHandler.stopHttpServer();
                logger.info("project exit successfully");
                break;
            } else {
                try {
                    logger.info("waiting...." + HttpSe2DBHandler.result.size());
                    Thread.sleep(60000);
                } catch (Exception ex) {
                }
            }
        }
    }

    private static void init() throws Exception {
        String configurationFileName = "ban-zzpt-metadata-db.properties";
        logger.info("TheFullFileName is  " + Http2MetaDB.confPath + File.separator + configurationFileName);
        Configuration conf = Configuration.getConfiguration(Http2MetaDB.confPath + File.separator + configurationFileName);
        if (conf == null) {
            throw new Exception("reading " + configurationFileName + " is failed");
        }

        logger.info("initializng runtime enviroment...");
        if (!RuntimeEnv.initialize(conf)) {
            throw new Exception("initializng runtime enviroment is failed");
        }
        logger.info("register shutdown hook");
        KillHandler killHandler = new KillHandler();
        killHandler.registerSignal("TERM");
        logger.info("register shutdown hook successfully");
    }

    public static void stop() {
        stopped = true;
    }

    public static Map getTableHandlerSet() {
        return httpSe2DBHandlerSet;
    }
}
